// DOM元素
const form = document.getElementById('contributionForm');
const previewGrade = document.getElementById('previewGrade');
const previewClass = document.getElementById('previewClass');
const previewName = document.getElementById('previewName');
const previewTitle = document.getElementById('previewTitle');
const previewCategory = document.getElementById('previewCategory');
const previewContent = document.getElementById('previewContent');
const successModal = document.getElementById('successModal');
const submissionId = document.getElementById('submissionId');

// 年级和班级的选项
const gradeOptions = {
    '1': '一年级',
    '2': '二年级',
    '3': '三年级',
    '4': '四年级',
    '5': '五年级',
    '6': '六年级',
    '7': '七年级',
    '8': '八年级',
    '9': '九年级'
};

const classOptions = {
    '1': '1班',
    '2': '2班',
    '3': '3班',
    '4': '4班',
    '5': '5班'
};

const categoryOptions = {
    '1': '校园故事',
    '2': '学习心得',
    '3': '科技创新',
    '4': '艺术文化',
    '5': '体育活动',
    '6': '其他'
};

// 监听表单变化，实时更新预览
form.addEventListener('input', updatePreview);
form.addEventListener('change', updatePreview);

// 更新预览内容
function updatePreview() {
    const grade = form.grade.value;
    const classValue = form['class'].value;
    const name = form.name.value;
    const title = form.title.value;
    const category = form.category.value;
    const content = form.content.value;

    previewGrade.textContent = grade ? `年级：${gradeOptions[grade]}` : '年级：-';
    previewClass.textContent = classValue ? `班级：${classOptions[classValue]}` : '班级：-';
    previewName.textContent = name ? `姓名：${name}` : '姓名：-';
    previewTitle.textContent = title ? title : '标题：-';
    previewCategory.textContent = category ? `分类：${categoryOptions[category]}` : '分类：-';
    previewContent.textContent = content ? content : '内容预览将在这里显示...';
}

// 表单提交处理
form.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // 构建提交数据
    const formData = {
        grade: form.grade.value,
        class: form['class'].value,
        name: form.name.value,
        title: form.title.value,
        category: form.category.value,
        content: form.content.value,
        submittedAt: new Date().toISOString()
    };
    
    try {
        // 实际API调用
        const response = await fetch('/api/submissions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.error || '提交失败');
        }
        
        const result = await response.json();
        
        // 检查响应结构，安全获取id
        const id = result.id ?? '无法获取编号';
        
        // 显示成功模态框
        submissionId.textContent = id;
        showModal();
        
        // 重置表单
        form.reset();
        updatePreview();
        
    } catch (error) {
        console.error('提交错误:', error);
        alert('提交失败: ' + (error.message || '请稍后重试'));
    }
});

// 显示模态框
function showModal() {
    successModal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// 关闭模态框
function closeModal() {
    successModal.style.display = 'none';
    document.body.style.overflow = '';
}

// 点击模态框外部关闭
window.addEventListener('click', (e) => {
    if (e.target === successModal) {
        closeModal();
    }
});

// 按ESC键关闭模态框
window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && successModal.style.display === 'flex') {
        closeModal();
    }
});

// 初始化预览
updatePreview();

// 添加平滑滚动效果
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

// 表单验证增强
const requiredFields = document.querySelectorAll('[required]');
requiredFields.forEach(field => {
    field.addEventListener('focus', () => {
        field.parentElement.classList.add('focused');
    });
    
    field.addEventListener('blur', () => {
        field.parentElement.classList.remove('focused');
        if (field.value.trim() === '' && field.hasAttribute('required')) {
            field.classList.add('error');
        } else {
            field.classList.remove('error');
        }
    });
});